package com.springboot.codeminestarter.codemine.wrapper;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisWrapper<K, V> {

    @Resource
    private RedisTemplate<K, V> redisTemplate;

    // Value Operation

    /**
     * 存Value值
     */
    public void putValue(K key, V value) {

        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 获取值
     */
    public V getValue(K key) {

        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 存Value值并设置过期时间
     */
    public void putValueWithExpireTime(K key, V value, long expireTime, TimeUnit timeUnit) {

        redisTemplate.opsForValue().set(key, value, expireTime, timeUnit);
    }

    /**
     * 获取Key过期时间
     */
    public Long getExpireTimeWithTimeUnit(K key, TimeUnit timeUnit) {

        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 移除Key
     */
    public Boolean delWithKey(K key) {

        return redisTemplate.delete(key);
    }

    /**
     * Key是否存在
     */
    public Boolean hasKey(K key) {

        return redisTemplate.hasKey(key);
    }

    /**
     * setNX命令
     */
    public Boolean putIfAbsentWithExpireTime(K key, V value, long expireTime, TimeUnit timeUnit) {


        return redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, timeUnit);
    }

    // Hash Operation

    public void putHash(K key, K hKey, V hval) {

        redisTemplate.opsForHash().put(key, hKey, hval);
    }

    public void getHash(K key, K hKey) {

        redisTemplate.opsForHash().get(key, hKey);
    }

    public void hasKey(K key, K hKey) {

        redisTemplate.opsForHash().hasKey(key, hKey);
    }

    public void delKey(K key, K hKey) {

        redisTemplate.opsForHash().delete(key, hKey);
    }

    public Boolean putHashIfAbsent(K key, K hKey, V hval) {

        return redisTemplate.opsForHash().putIfAbsent(key, hKey, hval);
    }

    /**
     * 设置K得过期时间
     */
    public Boolean expireWithTime(K key, long timeout, TimeUnit timeUnit) {

        return redisTemplate.expire(key, timeout, timeUnit);
    }

    // List Operation

    public Long leftPush(K key, V value) {

        return redisTemplate.opsForList().leftPush(key, value);
    }

    public V leftPop(K key) {

        return redisTemplate.opsForList().leftPop(key);
    }

    public V leftPopWithExpireTime(K key, long expireTime, TimeUnit timeUnit) {

        return redisTemplate.opsForList().leftPop(key, expireTime, timeUnit);
    }

    public Long rightPush(K key, V value) {

        return redisTemplate.opsForList().rightPush(key, value);
    }

    public V rightPop(K key) {

        return redisTemplate.opsForList().rightPop(key);
    }
}
